import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.log4j.Logger;

public class JdbcUtil {
	private static Logger logger = Logger.getLogger(JdbcUtil.class);

	private static String driverClass;
	private static String url;
	private static String user;
	private static String pwd;
	private static Properties prop = new Properties();

	static {
		InputStream in = JdbcUtil.class.getResourceAsStream("/dbconfig.properties");
		try {
			prop.load(in);
			driverClass = prop.getProperty("jdbc.driverClassName");
			url = prop.getProperty("jdbc.url");
			user = prop.getProperty("jdbc.username");
			pwd = prop.getProperty("jdbc.password");
		} catch (IOException e) {
			System.out.println("无法获得数据库连接!");
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static Connection getDBConn() {
		Connection conn = null;
		try {
			Class.forName(driverClass).newInstance();
			conn = DriverManager.getConnection(url, user, pwd);
		} catch (Exception e) {
			logger.error("Exception:", e);
		}
		return conn;
	}

	/**
	 * 释放资源
	 * 
	 * @param rs
	 *            结果集
	 * @param st
	 * @param conn
	 *            连接
	 */
	public static void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if (conn != null)
						conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		getDBConn();
	}
}
